package com.koron.order.orderAsset.service;

import com.koron.bean.base.Response;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import com.koron.order.defect.mapper.DefectMapper;
import com.koron.order.orderAsset.bean.OrderAsset;
import com.koron.order.orderAsset.feign.SystemFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderAssetServiceImpl implements OrderAssetService, SchedulingConfigurer {

    // corn 表达式：0 0 1 1 * ?，每个月的1号凌晨1点
    @Value(value = "${order.asset.sync:0 0 1 1 * ?}")
    private String corn;

    // 数据源标识
    @Value(value = "${order.asset.ds:water_02}")
    private List<String> dsList;

    // 默认是否启动
    @Value(value = "${order.asset.start:false}")
    private volatile boolean start;

    public static final String ORDERASSET_PREFIX = "GDZC";

    @Autowired
    private SystemFeignClient systemFeignClient;

    @Override
    public void syncDefectOrder() {
        for (String dsFlag : dsList) {
            log.info("OrderAssetServiceImpl:syncDefectOrder=>{}", dsFlag);
            try (SessionFactory sessionFactory = new SessionFactory()) {
                sessionFactory.setDbEnv(dsFlag);
                DefectMapper mapper = sessionFactory.getMapper(DefectMapper.class);
                ArrayList<OrderAsset> orderAssets = mapper.selectDefectOrderAsset();
                orderAssets.stream().forEach(o -> {
                    // 手动处理typeName 中包括英文括号导致生成的sql执行失败
                    if (o.getTypeName().contains("(")){
                        o.setTypeName(StringUtils.replace(o.getTypeName(),"(","（"));
                    }
                    if (o.getTypeName().contains(")")){
                        o.setTypeName(StringUtils.replace(o.getTypeName(),")","）"));
                    }
                    o.setId(CodeTools.getCode32()); // 设置主键
                    o.setCode(CodeTools.getCodeNo(ORDERASSET_PREFIX,3)); // 设置编号
                    o.setCreationMode(0); //设置来源类型
                    o.setSource(dsFlag); //设置来源
                });
                Response response = systemFeignClient.saveBatchOrderAsset(orderAssets);
                Assert.isTrue(response.getCode() == HttpStatus.OK.value(),"工单资产库更新失败！");
                log.info("OrderAssetServiceImpl:syncDefectOrder=>工单资产库更新成功!");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public void refreshCorn(String corn) {
        this.corn = corn;
    }

    @Override
    public void doTrigger() {
        OrderAssetService proxy = (OrderAssetService) AopContext.currentProxy();
        proxy.syncDefectOrder();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        registrar.addTriggerTask(() -> {
            log.info(String.valueOf(start));
            if (!start) {
                return;
            }
            syncDefectOrder();

        }, new CronTrigger(corn));
    }

    public void setStart(boolean start) {
        this.start = start;
    }

    public void setCorn(String corn){
        this.corn = corn;
    }
}
